<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
        <right-toolbar
          :showSearch.sync="showSearch"
          @queryTable="getList"
        ></right-toolbar>
    </el-row>
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="退订单号" prop="orderId">
        <el-input v-model="queryParams.orderId" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房源" prop="address">
        <el-input v-model="queryParams.address" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="住客名称" prop="lodgerName">
        <el-input v-model="queryParams.lodgerName" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="lodgerPhone">
        <el-input v-model="queryParams.lodgerPhone" placeholder="请输入" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="来源" prop="orderSource">
        <el-select v-model="queryParams.auditSource" placeholder="来源" clearable style="width: 240px">
          <!-- <el-option v-for="dict in dict.type.order_source" :key="dict.value" :label="dict.label" :value="dict.value" /> -->
          <el-option v-for="dict in dict.type.audit_source" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item label="入离时间">
        <el-date-picker v-model="dateRange" style="width: 240px" value-format="yyyy-MM-dd" type="daterange"
                        range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="状态" prop="auditProcess">
        <el-select v-model="queryParams.auditProcess" placeholder="请选择" clearable style="width: 240px">
          <el-option v-for="dict in dict.type.audit_process" :key="dict.value" :label="dict.label" :value="dict.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="roomList" ref="table">
      <el-table-column label="退订单号" prop="orderId" :show-overflow-tooltip="true"/>
      <el-table-column label="房源" prop="address" :show-overflow-tooltip="true"/>
      <el-table-column label="住客信息" prop="" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <div>{{ scope.row.lodgerName }}</div>
          <div>{{ scope.row.lodgerPhone }}</div>
        </template>
      </el-table-column>

      <el-table-column label="入离日期" prop="checkInTime">
        <template slot-scope="scope">
          <div>入：{{ scope.row.checkInTime | formatDate('YYYY-MM-DD') }}</div>
          <div>离：{{ scope.row.checkOutTime | formatDate('YYYY-MM-DD') }}</div>
        </template>
      </el-table-column>
      <el-table-column label="来源" prop="auditSource">
        <template slot-scope="scope">
          <!-- <dict-tag :options="dict.type.audit_source" :value="scope.row.auditSource" /> -->
          {{ auditSourceText(scope.row.auditSource) }}
        </template>
      </el-table-column>
      <el-table-column label="状态" prop="orderState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.audit_process" :value="scope.row.auditProcess"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleDetail(scope.row)">详情</el-button>
          <el-button size="mini" v-if="scope.row.auditProcess == 1" type="text"
                     @click="handleUpdate(scope.row)"
          >退订处理
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"
    />
    <el-dialog v-if="dialogVisible" :title="title" :visible.sync="dialogVisible" width="800px"
               :before-close="handleClose"
               :destroy-on-close="true"
    >
      <div>
        <el-descriptions title="" :column="2">
          <el-descriptions-item label="退订单号">{{
              detailInfo.orderId
            }}
          </el-descriptions-item>
          <el-descriptions-item label="订单号">{{
              detailInfo.order.orderId
            }}
          </el-descriptions-item>
          <el-descriptions-item label="房间">{{
              detailInfo.order.premisesAddress
            }}
          </el-descriptions-item>
          <el-descriptions-item label="预订房间">{{
              detailInfo.address
            }}
          </el-descriptions-item>
          <el-descriptions-item label="入离">
            {{ detailInfo.order.checkInTime | formatDate('MM-DD') }}至
            {{ detailInfo.order.checkOutTime | formatDate('MM-DD') }}
          </el-descriptions-item>
          <el-descriptions-item label="入住天数">
            {{
              DateDiff(
                detailInfo.order.checkInTime,
                detailInfo.order.checkOutTime
              )
            }}晚
          </el-descriptions-item>
          <el-descriptions-item label="申请来源">
            <!-- <dict-tag :options="dict.type.order_source" :value="detailInfo.order.orderSource" /> -->
            <dict-tag :options="dict.type.audit_source" :value="detailInfo.auditSource"/>
          </el-descriptions-item>
          <el-descriptions-item label="取消原因">
            {{ detailInfo.orderStateRecord.recordReason }}
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{
              detailInfo.createTime
            }}
          </el-descriptions-item>
        </el-descriptions>
        <el-tooltip class="item" effect="dark"
                    content="1.退订费按预订时选择的房间进行房费计算。2.已住房费按预订或续租时选择的房间进行房费计算"
                    placement="top-start"
        >
          <div>
            <!--            <el-button type="text">费用明细</el-button>-->
            <!--            <i class="el-icon-info"></i>-->
            <el-descriptions title="费用明细">
              <div slot="title">费用明细 <i class="el-icon-info"></i></div>
            </el-descriptions>

          </div>
        </el-tooltip>
        <price-table :data="detailInfo" :remainingSum.sync="remainingSum" :selection.sync="priceTableSelection"
                     :isCancal="isCancal" :isDetail="isDetail"
        />
      </div>
      <el-form :model="auditForm" :rules="rules" ref="auditForm" label-width="100px" class="demo-ruleForm"
               v-if="isCancal"
      >
        <el-form-item label="处理结果" prop="auditRecordState">
          <el-radio-group v-model="auditForm.auditRecordState">
            <el-radio label="2">退订通过</el-radio>
            <el-radio label="3">退订不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原因" prop="remark" v-if="auditForm.auditRecordState == 3">
          <el-input type="textarea" v-model="auditForm.remark"></el-input>
        </el-form-item>
      </el-form>
      <el-descriptions title="" :column="4">
        <el-descriptions-item label="总金额">{{
            detailInfo.order.totalRent+detailInfo.order.deposit
          }}
        </el-descriptions-item>
        <el-descriptions-item label="优惠金额">{{detailInfo.order.couponPrice}}</el-descriptions-item>
        <el-descriptions-item label="退还金额">{{refundSum}}</el-descriptions-item>
        <el-descriptions-item label="退还路径">原路返还</el-descriptions-item>
      </el-descriptions>
      <el-descriptions title="退订处理" :column="2" v-if="detailInfo.auditRecordState != 1">
        <el-descriptions-item label="处理结果">{{
            detailInfo.auditRecordState == 2 ? '退订通过' : '退订不通过'
          }}
        </el-descriptions-item>
        <el-descriptions-item label="处理人">{{
            detailInfo.operatorName
          }}
        </el-descriptions-item>
        <el-descriptions-item label="处理时间">{{
            detailInfo.updateTime
          }}
        </el-descriptions-item>
        <el-descriptions-item label="原因" v-if="detailInfo.auditRecordState == 3 ">{{
            detailInfo.remark
          }}
        </el-descriptions-item>
      </el-descriptions>

      <span slot="footer" class="dialog-footer" v-if="isCancal">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { cancelList, auditRecordInfo, auditRecord } from '@/api/order/continue'
import { DateDiff } from '@/utils/common/time'
import priceTable from '@/views/daily-rent/unsubscribe/components/price-table.vue'
import { debounce } from '@/utils'

export default {
  name: 'orderList',
  dicts: ['order_state', 'order_source', 'audit_process', 'audit_source'],
  components: {
    priceTable
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      roomList: [],
      // 弹出层标题
      title: '详情',
      // 是否显示弹出层
      open: false,
      // 当前选择
      current: 'all',
      // 是否显示为详情
      isDetail: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 日期范围
      dateRange: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roomNumber: undefined,
        premisesAddress: undefined,
        status: undefined,
        orderState: undefined,
        orderId: undefined,
        recordId: undefined, // 退订单号
        reserveUser: '',
        reserveUserPhone: '',
        orderSource: undefined,
        checkInTime: '',
        checkOutTime: ''
      },
      countHouseList: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      auditForm: {},
      // 表单校验
      rules: {
        auditRecordState: [
          { required: true, message: '选择处理结果', trigger: 'change' }
        ],
        remark: [{ required: true, message: '请填写原因', trigger: 'blur' }],
        roleSort: [
          { required: true, message: '角色顺序不能为空', trigger: 'blur' }
        ]
      },
      detailDialogVisible: false,
      orderId: '',
      openChangeHouse: false,
      openEdit: false,
      orderInfo: {},
      addDialogVisible: false, //新建弹窗，
      openmembershipRegistration: false,
      isCancal: false, //是否退订
      dialogVisible: false,
      detailInfo: {},
      remainingSum: 0,
      priceTableSelection: [],
      auditSourceList: [
        { label: '小程序退订', value: 1 },
        { label: '企业端退订', value: 2 }
      ]
    }
  },
  computed: {
    auditSourceText() {
      return (value) => {
        let obj = this.auditSourceList.find(item => item.value == value)
        return obj ? obj.label : ''
      }
    },
    // 退还金额计算
    refundSum() {
      //获取不需要退订费用id
      let noRefundDetailsIds = []
      this.priceTableSelection.map(item=>{
        if(item.parentKey == 'unsubscribeRefundItem'){
          noRefundDetailsIds.push(item.id);
        }
      })
      console.log('noRefundDetailsIds',noRefundDetailsIds)
      if(this.detailInfo.orderRefundDetailsList.length === noRefundDetailsIds.length){
        return this.remainingSum
      }else{
        return this.remainingSum - this.detailInfo.order.couponPrice
      }
    }
  },
  created() {
    this.getList()
  },
  activated() {
    this.getList()
  },
  methods: {
    DateDiff: DateDiff,
    submit: debounce(function() {
      this.$refs['auditForm'].validate((valid) => {
        if (valid) {
          //获取不需要退订费用id
          let noRefundDetailsIds = []
          this.priceTableSelection.map(item=>{
            if(item.parentKey == 'unsubscribeRefundItem'){
              noRefundDetailsIds.push(item.id);
            }
          })
          //
          //获取所有费用id
          let ids = this.detailInfo.orderRefundDetailsList.map(item=>{
            return item.id
          })
          //获取未选中的费用(未选中即为不扣除的费用,即退订费用)
          let refundDetailsIds = ids.filter(item=>{
            return !noRefundDetailsIds.includes(item)
          })
          //
          console.log('ids:所有',ids,'noRefundDetailsIds:不退',noRefundDetailsIds,'refundDetailsIds:退',refundDetailsIds)

          let form = { ...this.detailInfo }
          // form.refundDetailsIds = refundDetailsIds
          form.refundDetailsIds = noRefundDetailsIds
          form.auditRecordState = this.auditForm.auditRecordState
          form.remark = this.auditForm.remark

          console.log('form', form)
          auditRecord(form).then((res) => {
            this.$message.success(res.msg || '操作成功')
            this.dialogVisible = false
            this.getList()
          })
        }
      })
    }, 500, true),
    handleClose() {
      this.dialogVisible = false
    },
    dialogClose() {
      this.openChangeHouse = false
      this.openEdit = false
      this.openmembershipRegistration = false
      this.getList()
    },
    stateHandel(i) {
      console.log('i', i)
      if (i == 'all') {
        this.queryParams.auditRecordState = ''
      } else {
        let auditRecordState = this.dict.type.audit_process[i].value
        this.queryParams.auditRecordState = auditRecordState
      }

      this.handleQuery()
    },
    /** 查询列表 */
    getList() {
      this.loading = true
      this.queryParams.checkInTime = this.dateRange[0]
      this.queryParams.checkOutTime = this.dateRange[1]
      cancelList(this.queryParams, this.dateRange).then((response) => {
        this.roomList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.orderId = ''
      this.addDialogVisible = true
    },
    // 详情操作
    handleDetail(row) {
      this.orderId = row.orderId
      this.title = '详情'
      this.isCancal = false

      auditRecordInfo(row.recordId).then((res) => {
        this.detailInfo = res.data
        this.isDetail = true
        this.dialogVisible = true
      })
    },
    /** 编辑按钮操作 */
    handleUpdate(row) {
      this.orderInfo = row
      auditRecordInfo(row.recordId).then((res) => {
        this.detailInfo = res.data
        this.title = '退订信息'
        this.isDetail = false
        this.isCancal = true
        this.dialogVisible = true
      })
    },
    //换房操作
    handleChangeHouse(row) {
      this.orderInfo = row
      this.openChangeHouse = true
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'enterprise/order/order/export',
        {
          ...this.queryParams
        },
        `订单_${new Date().getTime()}.xlsx`
      )
    }
  }
}
</script>
<style lang="scss" scoped>
.title {
  font-size: 14px;
  font-weight: 500;
  color: #666;
}

.total {
  font-size: 18px;
  font-weight: 500;
  color: #333;
  margin-top: 6px;
}

.left-border {
  border-left: 1px solid #999;
}

.right-border {
  border-right: 1px solid #999;
}

.info {
  padding: 10px 15px;
  margin: 15px 0;
  background: #e6f7ff;
  color: #1890ff;

  span {
    color: #565c5f;
  }

  .clear {
    margin-left: 20px;
    cursor: pointer;
  }
}
</style>
